package gui.framework.file;

import gui.Context;

/**
 * 应用路径相关工具类
 * 
 * @author chenj_000
 *
 */
public class PathUtils {
	private static final boolean jar;

	static {
		jar = getClassPath(PathUtils.class).startsWith("file");
	}

	/**
	 * 获得当前字节码文件所在目录
	 * 
	 * @param cls
	 * @return
	 */
	public static String getClassPath(Class<?> cls) {
		return cls.getResource("").getPath();
	}

	/**
	 * 获得字节码文件所在的包名
	 * 
	 * @param cls
	 * @return
	 */
	public static String getPackageName(Class<?> cls) {
		return cls.getPackage().getName();
	}

	/**
	 * 将包名转换为应用名
	 * 
	 * @param packageName
	 * @return
	 */
	public static String packageNameToPath(String packageName) {
		return "/" + packageName.replaceAll("\\.", "/");
	}

	/**
	 * 获得当前应用所在的路径
	 * 
	 * @param cls
	 * @return
	 */
	public static String getApplicationPath(Class<? extends Context> cls) {
		if (jar) {
			String[] split = getClassPath(cls).split("/");
			String path = "/";
			for (int i = 1; i < split.length - 2; i++) {
				path += (split[i] + "/");
			}
			return path;
		} else {
			String classPath = getClassPath(cls);
			String packageName = getPackageName(cls);
			String packagePath = packageNameToPath(packageName);
			return classPath.substring(0, classPath.lastIndexOf("bin" + packagePath));
		}
	}
}
